package com.atguigu.msmservice.controller;

import com.atguigu.common.R;
import com.atguigu.msmservice.service.EmailService;
import com.atguigu.msmservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author panghl
 * @Date 2021/2/3 16:51
 * @Description 登录注册发送邮件
 **/
@RestController
@RequestMapping("edumsm/email")
@Api(tags = {"在线教育邮件管理"})
public class EmailController {

    @Autowired
    private EmailService emailService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/{sendTo}")
    public R sendEmail(@PathVariable("sendTo") String sendTo) {
        String code = redisTemplate.opsForValue().get(sendTo);
        if (!StringUtils.isEmpty(code)) {
            R.ok();
        }
        code = RandomUtil.getSixBitRandom();
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        boolean isSuccess = emailService.sendCodeByEmail(map, sendTo);
        if (isSuccess) {
            redisTemplate.opsForValue().set(sendTo,code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error();
        }
    }

}
